#import <Foundation/Foundation.h>
#import <objc/runtime.h>

#import "FWPreferences.h"


static NSString* const kPrefsDir = @"/private/var/mobile/Library/Caches";

@implementation FWPreferences

@synthesize preferences, filename;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithPreferences:(NSDictionary*)pref 
{
    if ((self = [super init])) {
        [pref retain];
        preferences = pref;
    }
    
    return self;
}

- (id)initWithFile:(NSString*)file
{
    if ((self = [super init])) {
        BOOL isDirectory;
        if ([[NSFileManager defaultManager] fileExistsAtPath:kPrefsDir isDirectory:&isDirectory] && isDirectory)
            filename = [kPrefsDir stringByAppendingFormat:@"/%@", file];
        else
            filename = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingFormat:@"/Documents/%@", file];
        [filename retain];
        
        NSDictionary* prefs = [NSDictionary dictionaryWithContentsOfFile:filename];
        [prefs retain];

        preferences = prefs;
    }
    
    return self;
}

- (void)dealloc
{
    [preferences release];
    [filename release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Persistence to storage

- (void)persist
{
    if (filename)
        [preferences writeToFile:filename atomically:YES];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Attribute access

- (NSString*)stringValue:(NSString*)name withDefault:(NSString*)def
{
    if (NSString* n = [preferences valueForKey:name])
        return n;
    return def;
}

- (BOOL)boolValue:(NSString*)name withDefault:(BOOL)def
{
    if (NSNumber* n = [preferences valueForKey:name])
        return n.boolValue;
    return def;
}

- (int)intValue:(NSString*)name withDefault:(int)def
{
    if (NSNumber* n = [preferences valueForKey:name])
        return n.intValue;
    return def;
}

@end
